package com.ctshk.rpc.finance.service.impl;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctshk.common.dto.Result;
import com.ctshk.common.enums.BusinessTypeCode;
import com.ctshk.common.enums.OrderConfirmationStatus;
import com.ctshk.common.enums.SystemBusinessType;
import com.ctshk.common.enums.SystemError;
import com.ctshk.common.exception.BusinessException;
import com.ctshk.common.model.PageResponse;
import com.ctshk.common.utils.SnowflakeIdWorker;
import com.ctshk.rpc.finance.dto.bill.BillRejectDTO;
import com.ctshk.rpc.finance.dto.bill.BillRejectDetailDTO;
import com.ctshk.rpc.finance.entity.FinanceBill;
import com.ctshk.rpc.finance.entity.FinanceBillReject;
import com.ctshk.rpc.finance.mapper.FinanceBillMapper;
import com.ctshk.rpc.finance.mapper.FinanceBillRejectMapper;
import com.ctshk.rpc.finance.req.bill.BillRejectAddReq;
import com.ctshk.rpc.finance.req.bill.BillRejectDetailReq;
import com.ctshk.rpc.finance.service.IFinanceBillRejectService;
import com.ctshk.rpc.order.air.req.ReceivePaymentConfirmReq;
import com.ctshk.rpc.order.air.service.IAirOrderService;
import com.ctshk.rpc.order.airexpress.service.IAirportExpressOrderCollectionService;
import com.ctshk.rpc.order.bus.service.IBusOrderCollectionService;
import com.ctshk.rpc.order.custom.service.ICustomizedOrderCollectionService;
import com.ctshk.rpc.order.goods.service.IOrderService;
import com.ctshk.rpc.order.hotel.service.IHotelOrderCenterService;
import com.ctshk.rpc.order.localfun.service.ILocalFunOrderCollectionService;
import com.ctshk.rpc.order.scenic.req.ScenicOrderCollectionRejectReq;
import com.ctshk.rpc.order.scenic.service.IScenicOrderCollectionService;
import com.ctshk.rpc.order.scenic.service.IScenicOrderService;
import com.ctshk.rpc.order.ship.service.IShipOrderCollectionService;
import com.ctshk.rpc.order.tour.service.ISeriesOrderCollectionService;
import com.ctshk.rpc.order.train.service.ITrainOrderCollectionService;
import com.ctshk.rpc.system.dto.UserDTO;
import com.ctshk.rpc.system.service.ISysUserService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Objects;


/**
 * <p>
 * 认款驳回记录 服务实现类
 * </p>
 *
 * @author 叶冠峰
 * @since 2021-04-19
 */
@DubboService
public class FinanceBillRejectServiceImpl extends ServiceImpl<FinanceBillRejectMapper, FinanceBillReject> implements IFinanceBillRejectService {

    @Autowired
    private FinanceBillRejectMapper billRejectMapper;
    @Autowired
    private FinanceBillMapper billMapper;

    @DubboReference
    private ISysUserService sysUserService;
    //机票
    @DubboReference
    private IAirOrderService airOrderService;
    //定制报团
    @DubboReference
    private ICustomizedOrderCollectionService customizedOrderCollectionService;
    //旅行团
    @DubboReference
    private ISeriesOrderCollectionService seriesOrderCollectionService;
    //门票
    @DubboReference
    private IScenicOrderCollectionService scenicOrderCollectionService;
    //机场快线
    @DubboReference
    private IAirportExpressOrderCollectionService airportExpressOrderCollectionService;
    @DubboReference
    private ILocalFunOrderCollectionService localFunOrderCollectionService;
    @DubboReference
    private IBusOrderCollectionService busOrderCollectionService;
    @DubboReference
    private IScenicOrderService scenicOrderService;
    @DubboReference
    private IShipOrderCollectionService shipOrderCollectionService;
    @DubboReference
    private ITrainOrderCollectionService trainOrderCollectionService;
    @DubboReference
    private IOrderService orderService;
    @DubboReference
    private IHotelOrderCenterService hotelOrderCenterService;



    /**
     * 认款管理-驳回信息
     *
     * @param req
     * @return
     */
    @Override
    public Result<BillRejectDetailDTO> detail(BillRejectDetailReq req) {
        BillRejectDetailDTO dto = new BillRejectDetailDTO();
        Page<BillRejectDTO> iPage = new Page<>(req.getPageNo(), req.getPageSize());
        Page<BillRejectDTO> page = billRejectMapper.queryPageByBill(iPage, req.getBillId());
        if (CollectionUtils.isNotEmpty(page.getRecords())){
            dto.setRejectInfo(page.getRecords().get(0).getRejectInfo());
        }
        PageResponse<BillRejectDTO> result = new PageResponse<>(
                page.getRecords(),
                page.getCurrent() == 1,
                page.getTotal() <= (page.getCurrent() * page.getSize()),
                page.getTotal(),
                page.getCurrent(),
                page.getSize());
        dto.setPage(result);
        return Result.success(dto);
    }

    /**
     * 认款管理-驳回
     *
     * @param req
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result add(BillRejectAddReq req) {
        FinanceBill bill = billMapper.selectById(req.getBillId());
        if (bill == null || Objects.equals(bill.getIsDeleted(),1) || Objects.equals(bill.getBillType(),2)){
            throw new BusinessException(SystemError.FINANCE_BILL_17009);
        }
        if (bill.getConfirmId() != null){
            throw new BusinessException(SystemError.FINANCE_ERROR_17034);
        }
        //新增驳回记录
        FinanceBillReject reject = new FinanceBillReject();
        reject.setId(SnowflakeIdWorker.nextId());
        reject.setBillId(req.getBillId());
        reject.setRejectInfo(req.getRejectInfo());
        UserDTO userDTO = sysUserService.queryCacheUser(req.getUser().getId());
        if (userDTO != null){
            reject.setCreateUserName(userDTO.getFullName());
            reject.setCreateUserDept(userDTO.getDept());
        }
        reject.setCreateId(req.getUser().getId());
        reject.setGmtCreate(LocalDateTime.now());
        boolean save = save(reject);
        bill.setIsReject(1);
        bill.setModifiedId(req.getUser().getId());
        int update = billMapper.updateById(bill);
        if (!save || update <= 0){
            throw new BusinessException(SystemError.SYS_437);
        }
        //根据收退款单号和业务类型，调用驳回接口
        try {
            Integer businessType = bill.getBusinessType();
            Result result = null;
            if (Objects.equals(businessType, SystemBusinessType.AIR_TICKET.getCode())){
                //机票
                ReceivePaymentConfirmReq req1 = new ReceivePaymentConfirmReq();
                req1.setCollectionNumber(bill.getBillNumber());
                req1.setRejectInfo(req.getRejectInfo());
                req1.setStatus(OrderConfirmationStatus.REJECTED);
                result = airOrderService.receivePaymentConfirm(req1);
            }else if (Objects.equals(businessType,SystemBusinessType.OUTBOUND_CUSTOMIZATION.getCode()) ||
                    Objects.equals(businessType,SystemBusinessType.INBOUND_CUSTOMIZATION.getCode()) ||
                    Objects.equals(businessType,SystemBusinessType.CONFERENCE_AWARDS.getCode())){
                //定制包团
                result = customizedOrderCollectionService.reject(bill.getBillNumber(), req.getRejectInfo(), req.getUser().getId());
            }else if (Objects.equals(businessType,SystemBusinessType.OUTBOUND_TRAVEL.getCode()) ||
                    Objects.equals(businessType,SystemBusinessType.INBOUND_TRAVEL.getCode())){
                //旅行团
                result = seriesOrderCollectionService.reject(bill.getBillNumber(), req.getRejectInfo(), req.getUser());
            }else if (Objects.equals(businessType,SystemBusinessType.HOTEL.getCode())){
                //酒店
                result = hotelOrderCenterService.finaceReject(bill.getBillNumber(),req.getUser().getId(),2,req.getRejectInfo());
            }else if (Objects.equals(businessType,SystemBusinessType.ATTRACTION_TICKET.getCode())){
                //景点门票
                result = scenicOrderService.rejectedMoney(bill.getBillNumber(), req.getRejectInfo());
            }else if (Objects.equals(businessType,SystemBusinessType.AIR_EXPRESS.getCode())){
                //机场快线
                result = airportExpressOrderCollectionService.rejectPayment(bill.getBillNumber(),req.getUser().getId(),req.getRejectInfo());
            }else if (Objects.equals(businessType,SystemBusinessType.LOCAL_FUN.getCode())){
                //当地玩乐
                result = localFunOrderCollectionService.rejectPayment(bill.getBillNumber(),req.getUser().getId(),req.getRejectInfo());
            }else if (Objects.equals(businessType,SystemBusinessType.SHIP_TICKET.getCode())){
                //船票
                result = shipOrderCollectionService.rejectPayment(bill.getBillNumber(), req.getUser().getId(), req.getRejectInfo());
            }else if (Objects.equals(businessType,SystemBusinessType.BUS_TICKET.getCode())){
                //巴士
                result = busOrderCollectionService.rejectPayment(bill.getBillNumber(), req.getUser().getId(), req.getRejectInfo());
            }else if (Objects.equals(businessType,SystemBusinessType.TRAIN_TICKET.getCode())){
                //火车票
                result = trainOrderCollectionService.rejectPayment(bill.getBillNumber(), req.getUser().getId(), req.getRejectInfo());
            }else if (Objects.equals(businessType,SystemBusinessType.COMMODITY.getCode())){
                //商品
                result = orderService.rejectPayment(bill.getBillNumber(), req.getUser().getId(), req.getRejectInfo());
            }
            if (result == null || !result.isSuccess()){
                return result;
            }
        }catch (Exception e){
            log.error(e.getMessage());
            System.err.println("业务类型：{ " + bill.getBusinessType() + " },错误信息：{ "+e.getMessage()+" }");
            throw new BusinessException(SystemError.SYS_437);
        }
        return Result.success(reject.getId());
    }
}
